package gui

import (
	"os/exec"
	"wxp2p/clientN"
	"wxp2p/uiapp/generator"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

func remoteConWindow(gVars *GlobalVars) fyne.CanvasObject {
	// myApp := gVars.APP
	// 控制远程设备
	remoteClientId := binding.NewString()
	remoteClientIdEntry := widget.NewEntryWithData(remoteClientId)
	rPort := binding.NewString()
	rPort.Set("3389")
	lPort := binding.NewString()
	lPort.Set("4389")
	logStr := binding.NewString()
	logRow := widget.NewLabelWithData(logStr)
	logRow.TextStyle.Bold = true

	linkBtn := widget.NewButtonWithIcon("连接", theme.LoginIcon(), func() {
		clientId, _ := remoteClientId.Get()
		rport, _ := rPort.Get()
		lport, _ := lPort.Get()
		if gVars.client != nil {
			gVars.client.ClientId = clientId
			gVars.client.StopRun()
		} else {
			gVars.client = clientN.NewClientClient(gVars.signalAddr, remoteClientIdEntry.Text)
			gVars.client.OnStatusChange(func(log string) {
				logStr.Set(log)
			})
		}
		gVars.client.ServerAddr = gVars.signalAddr
		gVars.client.Run()
		gVars.client.CreateDataChannel("", rport, "", lport)
	})
	unlinkBtn := widget.NewButtonWithIcon("断开", theme.LogoutIcon(), func() {
		if gVars.client != nil {
			gVars.client.ClientId = remoteClientIdEntry.Text
			gVars.client.StopRun()
		}
	})

	idRow := container.NewBorder(nil, nil, canvas.NewText("远程主机标识", nil), container.NewHBox(linkBtn, unlinkBtn), remoteClientIdEntry)
	rPortRow := container.NewBorder(nil, nil, canvas.NewText("远程主机端口", nil), nil, widget.NewEntryWithData(rPort))
	lPortRow := container.NewBorder(nil, nil, canvas.NewText("本机映射端口", nil), nil, widget.NewEntryWithData(lPort))
	rConBtn := widget.NewButtonWithIcon("远程连接(win)", theme.ComputerIcon(), func() {
		lport, _ := lPort.Get()
		cmd := exec.Command("mstsc", "/v:127.0.0.1:"+lport)
		err := cmd.Start() //如果用start则直接向后运行
		if err != nil {
			logStr.Set(err.Error())
		}
	})
	return container.NewVBox(idRow, rPortRow, lPortRow, rConBtn, logRow)
}

func genClientId() string {
	config := generator.Config{}
	config.IncludeNumbers = true
	config.IncludeLowercaseLetters = false
	config.IncludeUppercaseLetters = false
	config.IncludeSymbols = false
	config.IncludeAllSymbols = false
	config.Duplicate = false

	config.ExcludeSimilarCharacters = true

	config.Length = 8

	g, _ := generator.New(&config)
	pwd, _ := g.Generate()
	return pwd
}
